/*==============================================
Author:       UnknownCreature1117
Filetype:     C source code
Environment:  Linux & Ubuntu
Tool:         Nvim
Email:        UnknownCreature1117@outlook.com
==============================================*/
#include"mkdir.h"

int makeDir(const char *path //文件路径
) {
  //1. 检查路径是否已经存在,已有目标文件夹，则返回报错
  struct stat st;
  if (stat(path, &st) == 0) {
    if (S_ISDIR(st.st_mode)) {
      printf("Directory: %s already exists\n", path);
      return -1;
    } else {
      fprintf(stderr, "Path exists but is not a directory: %s\n", path);
      return -2;
    }
  }

  char tmp[256];
  char *p = NULL;
  size_t len;

  snprintf(tmp, sizeof(tmp), "%s", path);//输入
  len = strlen(tmp);
  if (tmp[len - 1] == '/') {
    tmp[len - 1] = 0;
  }

  for (p = tmp + 1; *p; p++) {
    if (*p == '/') {
      *p = 0;
      mkdir(tmp, 0777);
      *p = '/';
    }
  }
  mkdir(tmp, 0777);
  return 0;
}


int removeDir(const char *path) {
  // 检查路径是否存在
  struct stat st;
  if (stat(path, &st) != 0) {
    perror("stat");
    fprintf(stderr, "Directory: %s doesn't exists", path);
    return -1;
  }

  // 检查是否是目录
  if (!S_ISDIR(st.st_mode)) {
    fprintf(stderr, "path is not a directory: %s\n", path);
    return -2;
  }

  // 尝试删除目录
  if (rmdir(path) == -1) {
    perror("rmdir");
    fprintf(stderr, "connot remove dicectory: %s\n", path);
    return -3;
  }

  printf("%sdelet success:\n", path);
  return 0;
}
